package com.zhao.kafka.mysql



import java.sql.{Connection, PreparedStatement}

import org.apache.commons.dbcp.BasicDataSource
import org.apache.log4j.Logger



/**
 * Description: JDBC连接工具类<br/>
 * Copyright (c) ，2020 ， 赵 <br/>
 * This program is protected by copyright laws. <br/>
 * Date： 2020/12/25 10:47
 * CREATE TABLE `topic_par_group_offset` (
 * `topic` varchar(255) NOT NULL,
 * `partition` int(11) NOT NULL,
 * `groupid` varchar(255) NOT NULL,
 * `offset` bigint(20) DEFAULT NULL,
 * PRIMARY KEY (`topic`,`partition`,`groupid`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
 *
 * @author 柒柒
 * @version : 1.0
 */

object JDBCCConnPool {

  val log: Logger = Logger.getLogger(JDBCCConnPool.getClass)
  var dataSource: BasicDataSource = null

  /**
   * 创建数据源
   * @return
   */
  def getDataSource(): BasicDataSource = {
    if (dataSource == null) {
      dataSource = new BasicDataSource()
      dataSource.setDriverClassName(ConfigConstants.driver)
      dataSource.setUrl(ConfigConstants.url)
      dataSource.setUsername(ConfigConstants.user)
      dataSource.setPassword(ConfigConstants.password)
      //dataSource.setMaxTotal(50)
      dataSource.setDefaultAutoCommit(true) //设置连接是否默认提交
      dataSource.setInitialSize(3) //指定初始化连接数
      dataSource.setMaxActive(5) //指定最大的连接数
      dataSource.setMinIdle(3) //指定最小空闲数
      dataSource.setMaxIdle(10) //指定最大空闲数
      //dataSource.setMaxWaitMillis(2 * 10000)
      dataSource.setRemoveAbandonedTimeout(180)
      //dataSource.setRemoveAbandonedOnBorrow(true)
      //dataSource.setRemoveAbandonedOnMaintenance(true)
      dataSource.setTestOnReturn(true)
      dataSource.setTestOnBorrow(true)
    }
    return dataSource
  }

  /**
   * 释放数据源
   */
  def closeDataSource() = {
    if (dataSource != null){
      dataSource.close()
    }
  }

  /**
   * 获取数据库连接
   * @return
   */
  def getConnection() = {
    var conn: Connection = null
    try {
      if (dataSource != null) {
        conn = dataSource.getConnection()
      } else {
        conn = getDataSource().getConnection()
      }
    } catch {
      case e: Exception =>{
        log.error(e.getMessage(),e)
      }
    }
    conn
  }

  /**
   * 关闭连接
   * @param ps
   * @param conn
   */
  def closeConnection(ps: PreparedStatement, conn: Connection) = {
    if (ps != null){
      try{
        ps.close()
      }catch{
        case e: Exception =>
          log.error("预编译SQL语句对象PreparedStatement关闭异常!" + e.getMessage)
      }
    }

    if (conn != null){
      try{
        conn.close()
      }catch{
        case e: Exception =>
          log.error("连接对象Connection关闭异常!" + e.getMessage)
      }
    }
  }
}















